package com.eqdd.yiqidian.ui.mine.setting.alarm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.bean.rebuild.RuleResultBean;
import com.eqdd.yiqidian.utils.PreferenceUtil;
import com.eqdd.yiqidian.utils.SPUtil;
import com.jhj.alive.AbsWorkService;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * Created by jhj on 18-5-22.
 */

public class AlarmManagerServcice extends AbsWorkService {

    //是否 任务完成, 不再需要服务运行?
    public static boolean sShouldStopService;
    public static Disposable sDisposable;
    public static final String ALARM_ACTION = "com.eqdd.yiqidian.alarm.clock";

    public static void stopService() {
        //我们现在不再需要服务运行了, 将标志位置为 true
        sShouldStopService = true;
        //取消对任务的订阅
        if (sDisposable != null) sDisposable.dispose();
        //取消 Job / Alarm / Subscription
        cancelJobAlarmSub();
    }

    /**
     * 是否 任务完成, 不再需要服务运行?
     *
     * @return 应当停止服务, true; 应当启动服务, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean shouldStopService(Intent intent, int flags, int startId) {
        return sShouldStopService;
    }


    @Override
    public void startWork(Intent intent, int flags, int startId) {

        sDisposable = Observable
                .interval(3, TimeUnit.SECONDS)
                //取消任务时取消定时唤醒
                .doOnDispose(AbsWorkService::cancelJobAlarmSub)
                .subscribe(count -> {
                    System.out.println("每 3 秒采集一次数据... count = " + count);
                    if (count > 0 && count % 18 == 0)
                        System.out.println("保存数据到磁盘。 saveCount = " + (count / 18 - 1));
                });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        boolean isAlarm = (Boolean) SPUtil.getParam(AppConstent.isAlarmManager, false);
        if (isAlarm) {
            timeHandle();
            Log.w("xxx", "易企点启动service");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void stopWork(Intent intent, int flags, int startId) {
        stopService();
    }

    /**
     * 任务是否正在运行?
     *
     * @return 任务正在运行, true; 任务当前不在运行, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean isWorkRunning(Intent intent, int flags, int startId) {
        //若还没有取消订阅, 就说明任务仍在运行.
        return sDisposable != null && !sDisposable.isDisposed();
    }

    @Override
    public IBinder onBind(Intent intent, Void v) {
        return null;
    }

    @Override
    public void onServiceKilled(Intent rootIntent) {
        System.out.println("保存数据到磁盘。");
    }


    private void timeHandle() {
        RuleResultBean bean = PreferenceUtil.find(AlarmManagerServcice.this, AppConstent.ruleResultBean, RuleResultBean.class);
        if (bean != null) {
            Calendar calendar = Calendar.getInstance();
            List<Integer> weekList = parseWeeks(bean.getWeeks());
            List<String> timeList = new ArrayList<>();
            List<RuleResultBean.TimesBean> times = bean.getTimes();
            for (RuleResultBean.TimesBean time : times) {
                timeList.add(time.getStartTime());
                timeList.add(time.getEndTime());
            }
            if (weekList.contains(calendar.get(Calendar.DAY_OF_WEEK))) {
                List<Long> list = getMills(timeList);
                Calendar now = Calendar.getInstance();
                long alarmTime = 0;
                for (int i = 0; i < list.size(); i++) {
                    long time = list.get(i) - 2 * 60 * 1000;
                    if (time > now.getTimeInMillis()) {
                        alarmTime = time;
                        break;
                    } else if (i == list.size() - 1) {
                        alarmTime = list.get(0) - 2 * 60 * 1000 + 24 * 60 * 60 * 1000;
                    }
                }
                Log.w("xxx", Build.BRAND);
                setAlertManager(alarmTime);
            }
        }
    }

    private void setAlertManager(long millis) {
        Intent intent = new Intent(ALARM_ACTION);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent
                .FLAG_CANCEL_CURRENT);
        AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        if (am == null) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, millis, sender);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setWindow(AlarmManager.RTC_WAKEUP, millis, 0, sender);
        } else {
            am.set(AlarmManager.RTC_WAKEUP, millis, sender);
        }
    }

    private List<Long> getMills(List<String> timeList) {
        List<Long> longs = new ArrayList<>();
        try {
            for (String s : timeList) {
                longs.add(getStringToMillis(s));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return longs;
    }

    public static long getStringToMillis(String str) throws ParseException {
        Calendar c = Calendar.getInstance();
        String[] array = str.split(":");
        c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(array[0]));
        c.set(Calendar.MINUTE, Integer.parseInt(array[1]));
        return c.getTimeInMillis();
    }

    private List<Integer> parseWeeks(String weeks) {
        String[] array = weeks.split(",");
        List<Integer> list = new ArrayList<>();
        for (String s : array) {
            if ("星期日".equals(s)) {
                list.add(1);

            }
            if ("星期一".equals(s)) {
                list.add(2);

            }
            if ("星期二".equals(s)) {
                list.add(3);

            }
            if ("星期三".equals(s)) {
                list.add(4);

            }
            if ("星期四".equals(s)) {
                list.add(5);

            }
            if ("星期五".equals(s)) {
                list.add(6);

            }
            if ("星期六".equals(s)) {
                list.add(7);

            }
        }
        return list;
    }


}
